package job.work.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public final class QrCodeUtils {

    /**
     * 生成二维码Png图片的Base64
     *
     * @param content 二维码内容
     * @param width   宽
     * @param height  高
     * @return 二维码Png图片的Base64
     */
    public static String generateQrCodeBase64(String content, int width, int height) {
        //设置图片的文字编码以及内边框
        Map<EncodeHintType, Object> hints = new HashMap<>();
        //编码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //边框距
        hints.put(EncodeHintType.MARGIN, 0);

        return generateQrCodeBase64(content, width, height, hints);
    }

    /**
     * 生成二维码Png图片的Base64
     *
     * @param content 二维码内容
     * @param width   宽
     * @param height  高
     * @param hints   自定义提供给编码器的其他参数
     * @return 二维码Png图片的Base64
     */
    public static String generateQrCodeBase64(String content, int width, int height, Map<EncodeHintType, Object> hints) {
        final BitMatrix bitMatrix;
        String qrCode = "";
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            return qrCode;
        }
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
            byte[] bytes = outputStream.toByteArray();
            // 2、将字节数组转为二进制
            BASE64Encoder encoder = new BASE64Encoder();
            qrCode = encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return qrCode;
    }

    public static void main(String[] args) {
        System.out.println(QrCodeUtils.generateQrCodeBase64("测试东西",200,200));
    }
}